'''
Created on 2014/5/27

@author: cat
'''


from http.server import HTTPServer 
from http.server import BaseHTTPRequestHandler

import SerialManager
import ModbusFormat


comport = SerialManager.Serial_Thread()
Modbus_packet = ModbusFormat.Modbus()

class HttpHandler(BaseHTTPRequestHandler):                           
    def do_GET(self):
        print(self.path)
        query = self.path.split('?')[1]
        urlquery = query.split(',')
        print(urlquery)
        
        #send code 200 response
        self.send_response(200)

        #send header first
        self.send_header('Content-type','text-html')
        self.end_headers()
        
        try:
            global Modbus_packet
            packet = Modbus_packet.get_packet(urlquery)
            print(packet)
            self.wfile.write("sending packet</br>".encode(encoding='utf_8'))
            self.wfile.write((''.join('{:02x}'.format(x) for x in packet)).encode(encoding='utf_8'))
            
            global comport
            comport.serial_write(packet)
            respond = comport.serial_read(Modbus_packet.respond_length)
            print(respond)
            self.wfile.write("reading respond</br>".encode(encoding='utf_8'))
            msg = ""
            if True:
                self.wfile.write((''.join('{:02x}'.format(x) for x in respond)).encode(encoding='utf_8'))
                msg = Modbus_packet.get_msg(respond)
            
                self.wfile.write("current value</br>".encode('utf_8'))
                self.wfile.write(msg.encode(encoding='utf_8'))
            else:
                self.wfile.write("No respond".encode('utf_8'))
        except:
            print("except server down")
            #self.server.shutdown()
        
if __name__ == '__main__':
    
    comport.serial_init("/dev/ttyUSB0")
    
    PORT = 8012
    while True:      
        try:
            httpd = HTTPServer(("192.168.1.106", PORT), HttpHandler)
            httpd.allow_reuse_address = True
            print(PORT)
            httpd.serve_forever()
            
        except:
            PORT = PORT + 1
            
    
    